#!/usr/bin/env python

import os.path
import shutil

from optparse import OptionParser
import ConfigParser

try: import json #python 2.6 included simplejson as json
except ImportError: import simplejson as json

def transform(filename, section):
    rfile = open(filename)

    # look for
    for line in rfile:
        if line.startswith("[" + section + "]"):
            print "Found section [" + section + "]"
            break

    columnheaders = rfile.next()
    if (columnheaders != ""):
        columns = columnheaders.rstrip().split(",")
        numberOfColumns = len(columns)
        print "Transforming " + str(numberOfColumns) + " Columns"

        wfile = open("TRANSFORM_" + get_filename(filename), "w")
        for i, column in enumerate(columns):
            if i > 0: wfile.write("\t")
            wfile.write(column)

        wfile.write("\n")

        for contentline in rfile:
            contents = contentline.rstrip().split(",")

            for i, value in enumerate(contents):
                if i > 0: wfile.write("\t")
                wfile.write(value)

            wfile.write("\n")

        wfile.close()

def get_filename(filename):
    lastslash = filename.rfind("/") + 1
    if lastslash < 0: lastslash = 0
    lastdot = filename.rfind(".")
    if lastdot < 0: lastdot = len(filename)

    f = filename[lastslash:lastdot].upper()
    return f.replace(" ", "_")

if __name__ == "__main__":
    parser = OptionParser(usage="%prog -s SECTION -f FILENAME")
    parser.add_option("-s", "--section", dest="section", help="Section to transform")
    parser.add_option("-f", "--targetFile", dest="targetFile", help="Target file")

    (options, args) = parser.parse_args()

    filename = options.targetFile
    if filename is None:
        print "===> ERROR: Specify path to file for import"
        parser.print_help()
        exit(-1)

    section = options.section
    if section is None:
        print "===> ERROR: Specify section to transform"
        parser.print_help()
        exit(-1)

    transform(filename, section)